import { Plugin, PluginKey } from "@rivet/state";
import { Step } from "@rivet/transform";

export const messageCountKey = new PluginKey("messageCount");
export const messageCountPlugin = new Plugin<number>({
  key: messageCountKey,
  state: {
    init(_config, state) {
      let count: number = 0;
      state.tr.doc.content.content[0].content.content.forEach((item) => {
        if (item.type.name === "qd") {
          count++;
        }
      });
      return count;
    },
    apply(_tr, _oldvalue, state) {
      let count: number = 0;
      state.tr.doc.content.content[0].content.content.forEach((item) => {
        if (item.type.name === "qd") {
          count++;
        }
      });
      return count;
    },
  },
  appendTransaction([tr], _oldState, _newState) {
    tr.transaction((_doc: any) => {
      tr.setNodeAttribute("4", {
        name: "我是测试" + tr.steps.length,
        email: "alice@example.com4",
      });
    });
    return tr;
  },
});

//历史记录插件
export const historyKey = new PluginKey("historyKey");
export const historyKeyPlugin = new Plugin<Step[]>({
  key: historyKey,
  state: {
    init(_config, _state) {
      return [];
    },
    apply(tr, _oldvalue, _state) {
      return tr.steps;
    },
  },
});
